package edu.goku.examples.httpsdemo.client;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import javax.net.ssl.*;
import java.io.IOException;
import java.io.InputStream;
import java.security.*;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

/**
 * @author fuyongde
 * @date 2020/12/6 19:14
 */
public class HttpsUtils {

    private OkHttpClient httpClient;

    public HttpsUtils() {
        this.httpClient = new OkHttpClient.Builder()
                .hostnameVerifier(hostnameVerifier())
                .sslSocketFactory(sslSocketFactory(), trustManager())
                .build();
    }

    public static void main(String[] args) throws IOException {
        HttpsUtils httpsUtils = new HttpsUtils();
        Request request = new Request.Builder()
                .url("https://localhost:8443/index/hello")
                .build();
        Response response = httpsUtils.httpClient.newCall(request).execute();
        System.out.println(response.body().string());
    }

    private static HostnameVerifier hostnameVerifier() {
        return (hostname, session) -> true;
    }

    private static SSLSocketFactory sslSocketFactory() {
        try (InputStream inputStream = HttpsUtils.class.getResourceAsStream("/certs/client.p12")) {
            //创建KeyStore，用来存储信任证书
            KeyStore keyStore = KeyStore.getInstance("PKCS12");
            keyStore.load(inputStream, "111111".toCharArray());

            KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            kmf.init(keyStore, "111111".toCharArray());

            String defaultAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
            TrustManagerFactory tmf = TrustManagerFactory.getInstance(defaultAlgorithm);
            tmf.init(keyStore);

            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new SecureRandom());

            return sslContext.getSocketFactory();
        } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException | UnrecoverableKeyException | IOException | CertificateException e) {
            throw new RuntimeException(e);
        }
    }

    private static X509TrustManager trustManager() {
        return new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] chain, String authType) {}

            @Override
            public void checkServerTrusted(X509Certificate[] chain, String authType) {}

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }
        };
    }
}
